package com.zx.flow.api.util;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import java.net.BindException;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

public class ValidUtil {

    /**
     * 缺少字段信息【不推荐是】
     *
     * @param bindingResult
     * @return
     */
    public static String getAllError(BindingResult bindingResult) {
        return bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";"));
    }

    public static String getError(BindingResult bindingResult) {
        return bindingResult.getFieldError().getField() // 校验的字段
                + bindingResult.getFieldError().getDefaultMessage();//校验失败的消息;
    }

    public static String getError(Set<ConstraintViolation<?>> violations) {
        return violations.stream().map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(";"));
    }

    public static String getError2(Set<ConstraintViolation<Object>> violations) {
        return violations.stream().map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(";"));
    }

    /**
     * 编程式参数校验[用于非controller接口]
     *
     * @param globalValidator 可以通过@Autowired注入
     * @param object
     * @param groupClasss
     * @return
     */
    public static void validate(Validator globalValidator, Object object, Class groupClasss) throws BindException {
        Set<ConstraintViolation<Object>> validate = globalValidator.validate(object, groupClasss);
        // 如果validate不为空，说明包含未校验通过的参数
        if (!validate.isEmpty()) {
            throw new BindException(ValidUtil.getError2(validate));
        }
    }
}
